package com.clhbolg.service.impl;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.clhbolg.constant.RedisConstant;
import com.clhbolg.service.WebReportService;
import com.clhbolg.util.IpUtils;
import com.ruoyi.common.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author cailinhu
 * @Description TODO
 * @Date 2023/3/10 14:58
 * @Version 1.0
 */
@Service
public class WebReportServiceImpl implements WebReportService {

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public void report() {
        HttpServletRequest request = ServletUtils.getRequest();
        String ip = ServletUtils.getClientIP(request);
        //这种需要访问第三接口
//        String address = AddressUtils.getRealAddressByIP(ip);
        UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        // 获取客户端操作系统
        String os = userAgent.getOs().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        String uuid = ip + browser+ os;
        String md5 = DigestUtils.md5DigestAsHex(uuid.getBytes());
        SetOperations setOperations = redisTemplate.opsForSet();
        if (!setOperations.isMember(RedisConstant.UNIQUE_VISITOR,md5)) {
            String ipSource = IpUtils.getIpSource(ip);
            if (StringUtils.isNotBlank(ipSource)) {
                //格式化地址
                String ipProvince = IpUtils.getIpProvince(ipSource);
                //保存一次浏览量
                redisTemplate.opsForHash().increment(RedisConstant.VISITOR_AREA, ipProvince, 1L);
            } else {
                //如果没有找到归属地也要保存
                redisTemplate.opsForHash().increment(RedisConstant.VISITOR_AREA, "未知", 1L);
            }
            //增加网站浏览总次数
            redisTemplate.opsForValue().increment(RedisConstant.BLOG_VIEWS_COUNT, 1);
            //记录机器信息，如果下次再重复进来则，不保存浏览信息
            redisTemplate.opsForSet().add(RedisConstant.UNIQUE_VISITOR, md5);
        }



    }
}
